<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\index\controller;

use think\facade\View;
use think\facade\Filesystem;
use app\index\BaseController;
use think\exception\ValidateException;
use app\index\addons\Login;
use app\index\model\Config;
use app\index\model\UserLog;
use app\index\model\UserGroup;
use app\index\model\User as UserModel;
use app\index\validate\User as UserValidate;
/**
 * 用户登录、注册、修改密码等
 */
class User  extends BaseController
{
    /**
     * 登录
     */
    public function login()
    {
        event("UserLoginInit");
        if ($this->request->isPost()) {
            try {
                $input = input();
                $scene = $this->isNeedVerification() === 1 ? 'captchalogin' : 'login';
                validate(UserValidate::class)->scene($scene)->check($input);
                $userInfo = UserModel::with(['group'])->withoutField('pay_paasword,password,login_ip')->where('account|email',$input['loginAccount'])->find();
                if ($userInfo) {
                    $password = UserModel::where('id', $userInfo['id'])->value('password');
                    if (password_verify($input['loginPassword'], $password)) {
                        if ($userInfo['status'] === 1) {
                            $userInfo->login_count = $userInfo->login_count + 1;
                            $userInfo->login_ip    = $this->request->ip();
                            $userInfo->login_time  = date('Y-m-d H:i:s');
                            $userInfo->save();
                            // 记录用户信息
                            session('index_user',$userInfo);
                            // 清除登录错误次数
                            Login::clearLoginErrorNum();
                            // 勾选两周内自动登录
                            Login::openAutomaticLogin($input);
                            return json(['status' => 'success', 'message' => '登录成功', 'url'=> $this->request->indexLastUrl()]);
                        } else {
                            $error = ['status' => 'error', 'message' => '账号审核中...'];
                        }
                    } else {
                        $error = ['status' => 'error', 'message' => '账号或密码错误'];
                    }
                } else {
                    $error = ['status' => 'error', 'message' => '账号或密码错误'];
                }
                // 设置当前ip登录错误次数
                Login::setLoginErrorNum();
                return json($error);
            } catch ( ValidateException $e ) {
                return json($e->getError());
            }
        } else {
            $userInfo = session('index_user');
            if (empty($userInfo)) {
                return View::fetch("user/login");
            } else {
                return redirect($this->request->indexLastUrl());
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Login::clearLoginStatus();
        return redirect(get_url("user/login"));
    }
    
    /**
     * 修改密码
     */
    public function password()
    {
        if ($this->request->isPost()) {
            try {
                $input = input();
                validate(UserValidate::class)->scene('password')->check($input);
                $code = Login::getEmailCode('index_password_code');
                if ($code == $input['code']) {
                    $save = UserModel::where('email',$input['email'])->find();
                    if ($save) {
                        $save->password = $input['password'];
                        $save->save();
                        Login::clearLoginStatus();
                        return json(['status' => 'success', 'message' => '修改成功']);
                    } else {
                        return json(['status' => 'error', 'message' => '该邮箱号未被注册！']);
                    }
                } else {
                    return json(["status"=>"error","message"=>"输入的验证码有误"]);
                }
            } catch ( ValidateException $e ) {
                return json($e->getError());
            }
        } else {
            return View::fetch("user/password");
        }
    }

    /**
     * 注册
     */
    public function register()
    {
        if ($this->request->isPost()) {
            try {
                $input = input();
                validate(UserValidate::class)->scene('register')->check($input);
                $code = Login::getEmailCode('index_register_code');
                if ($code == $input['code']) {
                    $account = UserModel::where('account', $input['account'])->value('id');
                    $email   = UserModel::where('email', $input['email'])->value('id');
                    if (! $account) {
                        if (! $email) {
                            $group    = UserGroup::where('default',1)->find();
                            $group_id = 0;
                            $integral = 0;
                            if ($group) {
                                $group_id = $group['id'];
                                $integral = $group['integral'];
                            }
                            $date = date('Y-m-d H:i:s');
                            $registerInfo = UserModel::create([
                                'group_id'         => $group_id,
                                'nickname'         => $input['account'],
                                'sex'              => 0,
                                'email'            => $input['email'],
                                'mobile'           => "",
                                'account'          => $input['account'],
                                'password'         => $input['password'],
                                'cover'            => "",
                                'describe'         => lang("This guy is lazy. He doesn't leave anything"),
                                'birthday'         => date('Y-m-d'),
                                'now_integral'     => $integral,
                                'history_integral' => $integral,
                                'balance'          => 0,
                                'pay_paasword'     => '',
                                'level'            => 0,
                                'login_ip'         => $this->request->ip(),
                                'login_count'      => 0,
                                'login_time'       => $date,
                                'update_time'      => $date,
                                'create_time'      => $date,
                                'status'           => 1,
                                'see'              => 0,
                                'field'            => [],
                            ]);
                            // 事件绑定
                            event("UserRegisterEnd", $registerInfo);
                            // 清除登录状态
                            Login::clearLoginStatus();
                            return json(['status' => 'success', 'message' => '注册成功，快去登录吧']);
                        } else {
                            return json(['status' => 'error', 'message' => '该邮箱号已经注册！']);
                        }
                    } else {
                        return json(['status' => 'error', 'message' => '该账号已经注册！']);
                    }
                } else {
                    return json(["status"=>"error","message"=>"输入的验证码有误"]);
                }
            } catch ( ValidateException $e ) {
                return json($e->getError());
            }
        } else {
            return View::fetch("user/register");
        }
    }

    /**
     * 发送注册邮箱验证码
     */
    public function sendRegisterEmailCode()
    {
        try {
            $input = input();
            validate(UserValidate::class)->scene('code')->check($input);
            $email = UserModel::where('email', $input['email'])->value('id');
            if (! $email) {
                $message = Login::sendEmailCode($input['email'], 'index_register_code', '注册');
                return json($message);
            } else {
                return json(['status' => 'error', 'message' => '该邮箱号已经注册！']);
            }
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 发送修改密码邮箱验证码
     */
    public function sendPasswordEmailCode()
    {
        try {
            $input = input();
            validate(UserValidate::class)->scene('code')->check($input);
            $email = UserModel::where('email', $input['email'])->value('id');
            if ($email) {
                $message = Login::sendEmailCode($input['email'], 'index_password_code', '修改密码');
                return json($message);
            } else {
                return json(['status' => 'error', 'message' => '该邮箱号未被注册！']);
            }
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 是否开启登录验证码
     * @return int
     */
    public function isNeedVerification()
    {
        $error_num = Login::getLoginErrorNum();
        if ($error_num > 5) {
            return 1;
        } else {
            return 0;
        }
    }
}